package ar.diegodob.charcas.model.player;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import ar.diegodob.charcas.model.exceptions.CharcasException;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.AudioDevice;
import javazoom.jl.player.FactoryRegistry;
import javazoom.jl.player.Player;
import javazoom.jl.player.jlp;

public class PlayerManager {

	private static PlayerManager instance;
	private Player player;
	
	private String fFilename = null;
	private boolean remote = false;

	public static PlayerManager getInstance() {
		if (instance == null) {
			instance = new PlayerManager();			
		}
		return instance;
	}

	private PlayerManager()
	{
	}

	public void play(String filename) throws CharcasException
	{
		fFilename = filename;
		try
		{
			System.out.println("playing "+fFilename+"...");
			InputStream in = null;
			if (remote == true) in = getURLInputStream();
			else in = getInputStream();
			AudioDevice dev = getAudioDevice();
			player = new Player(in, dev);
			player.play();
		}
		catch (IOException ex)
		{
			throw new CharcasException("Problem playing file "+fFilename, ex);
		}
		catch (Exception ex)
		{
			throw new CharcasException("Problem playing file "+fFilename, ex);
		}
	}

	/**
	 * Playing file from URL (Streaming).
	 */
	protected InputStream getURLInputStream()
		throws Exception
	{

		URL url = new URL(fFilename);
		InputStream fin = url.openStream();
		BufferedInputStream bin = new BufferedInputStream(fin);
		return bin;
	}

	/**
	 * Playing file from FileInputStream.
	 */
	protected InputStream getInputStream()
		throws IOException
	{
		FileInputStream fin = new FileInputStream(fFilename);
		BufferedInputStream bin = new BufferedInputStream(fin);
		return bin;
	}

	protected AudioDevice getAudioDevice()
		throws JavaLayerException
	{
		return FactoryRegistry.systemRegistry().createAudioDevice();
	}
	
	public void stop() {
		this.player.close();		
	}

}
